package at.hcmut.dev.mobile.barcamp;

import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.R.bool;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;

public class MainActivity extends MapActivity {

	Emergency em = new Emergency();
	private EditText txtMesseage;
	private MapController mc;
	private Button btnSend;
	private MapView mapView;
	protected LocationManager locationManager;
	private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in
																		// Meters
	private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in
																	// Milliseconds
	private GeoPoint p;
	private static final String SOAP_ACTION = "http://thanhphuongshop.com/mdc2011/Webservice/Add";
	private static final String METHOD_NAME = "Add";
	private static final String NAMESPACE = "http://thanhphuongshop.com/mdc2011/Webservice/";
	private static final String URL = "http://thanhphuongshop.com/mdc2011/Webservice/Emergency.asmx?wsdl";

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		btnSend = (Button) findViewById(R.id.btnSend);
		mapView = (MapView) findViewById(R.id.mapView);
		txtMesseage = (EditText) findViewById(R.id.txtMesseage);
		mc = mapView.getController();

		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
				MINIMUM_TIME_BETWEEN_UPDATES,
				MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, new MyLocationListener());

		// showCurrentLocation();
		startActivityForResult(new Intent(getApplicationContext(),
				MyLocationService.class), 1);
		btnSend.setOnClickListener(onclick);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 1 && resultCode == RESULT_OK) {
			Location location = CommonUtilities.location;

			if (location != null) {
				String message = String
						.format("Current Location \n Longitude: %1$s \n Latitude: %2$s",
								location.getLongitude(), location.getLatitude());
				Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG)
						.show();
				p = new GeoPoint((int) (location.getLatitude() * 1E6),
						(int) (location.getLongitude() * 1E6));
				em.setLat(location.getLatitude());
				em.setLng(location.getLongitude());
				mc.animateTo(p);
				mc.setZoom(19);

				MapOverlay mapOverlay = new MapOverlay();
				List<Overlay> listOfOverlays = mapView.getOverlays();
				listOfOverlays.clear();
				listOfOverlays.add(mapOverlay);
				mapView.invalidate();
			}
		}
	}

	private String getCurrentDateTime() {
		String s = "";
		Calendar c = Calendar.getInstance();
		s = s + c.get(Calendar.DATE) + "/";
		s = s + c.get(Calendar.MONTH) + "/";
		s = s + c.get(Calendar.YEAR) + "/ ";

		s = s + c.get(Calendar.HOUR) + ":";
		s = s + c.get(Calendar.MINUTE) + ":";
		s = s + c.get(Calendar.SECOND);
		return s;
	}

	OnClickListener onclick = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub

			TelephonyManager tel = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
			em.setPhone(tel.getLine1Number());
			em.setDate(getCurrentDateTime());
			em.setMessage(txtMesseage.getText().toString());
			System.out.println("?????????" + em.getLat() + ", " + em.getLng()
					+ ", " + em.getDate() + ", " + em.getPhone());
			new RequestAsynTask().execute(em);
		}
	};

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

	protected void showCurrentLocation() {

		Location location = locationManager
				.getLastKnownLocation(LocationManager.GPS_PROVIDER);

		if (location != null) {
			String message = String.format(
					"Current Location \n Longitude: %1$s \n Latitude: %2$s",
					location.getLongitude(), location.getLatitude());
			Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG)
					.show();
			p = new GeoPoint((int) (location.getLatitude() * 1E6),
					(int) (location.getLongitude() * 1E6));
			em.setLat(location.getLatitude());
			em.setLng(location.getLongitude());
			mc.animateTo(p);
			mc.setZoom(17);

			MapOverlay mapOverlay = new MapOverlay();
			List<Overlay> listOfOverlays = mapView.getOverlays();
			listOfOverlays.clear();
			listOfOverlays.add(mapOverlay);
			mapView.invalidate();
		}

	}

	private class RequestAsynTask extends AsyncTask<Emergency, Integer, Boolean> {

		@Override
		protected void onPostExecute(Boolean result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			Toast.makeText(getApplicationContext(), result.toString(), Toast.LENGTH_SHORT).show();
		}

		@Override
		protected Boolean doInBackground(Emergency... params) {
			// TODO Auto-generated method stub
			boolean result =  true;
			try {
				Emergency em = params[0];
				SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
		
 				
				request.addProperty("phonenumber", em.getPhone());
				request.addProperty("longitude", String.valueOf(em.getLng()));
				request.addProperty("latitude", String.valueOf(em.getLat()));
				request.addProperty("message", em.getMessage());

				SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
						SoapEnvelope.VER11);
				envelope.dotNet = true;
				envelope.setOutputSoapObject(request);

				HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
				androidHttpTransport.call(SOAP_ACTION, envelope);

				result = Boolean.valueOf(envelope.getResponse().toString());
				//SoapObject response = (SoapObject)envelope.getResponse();
				
			} catch (Exception e) {
				// TODO: handle exception
				result = false;
			}
			System.out.println(result + " ???????????????????????????");
			return result;
		}

	}

	private class MapOverlay extends com.google.android.maps.Overlay {

		@Override
		public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
				long when) {
			// TODO Auto-generated method stub
			super.draw(canvas, mapView, shadow, when);
			Point screenPts = new Point();
			mapView.getProjection().toPixels(p, screenPts);

			Bitmap bmp = BitmapFactory.decodeResource(getResources(),
					R.drawable.mapviewservice_pinicon_drag);
			canvas.drawBitmap(bmp, screenPts.x, screenPts.y - 72, null);
			return true;
		}

	}

	private class MyLocationListener implements LocationListener {

		public void onLocationChanged(Location location) {
			String message = String.format(
					"New Location \n Longitude: %1$s \n Latitude: %2$s",
					location.getLongitude(), location.getLatitude());
			Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG)
					.show();
		}

		public void onStatusChanged(String s, int i, Bundle b) {
			Toast.makeText(MainActivity.this, "Provider status changed",
					Toast.LENGTH_LONG).show();
		}

		public void onProviderDisabled(String s) {
			Toast.makeText(MainActivity.this,
					"Provider disabled by the user. GPS turned off",
					Toast.LENGTH_LONG).show();
		}

		public void onProviderEnabled(String s) {
			Toast.makeText(MainActivity.this,
					"Provider enabled by the user. GPS turned on",
					Toast.LENGTH_LONG).show();
		}
	}
}